import Layout from '@/layout'
import { defineStore } from 'pinia'
import { LoginRegister, userMenu } from '@/api/login'
import type { UserInfoParams, UserInfoData } from '@/api/user'
import type { LoginPort } from '@/api/login'
import { ElMessage } from 'element-plus'
import { constantRoutes as staticRoutes, dynamicRoutes as allAsyncRoutes, anyRoute } from '@/router'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import cloneDeep from 'lodash/cloneDeep'
import JMessage from '@/utils/JMessage'
import request from '@/utils/request'
import { fullFilePath } from '@/utils/tools'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('../views/**/*.vue')

// 动态注册路由
function addRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((route) => {
    router.addRoute(route)
  })
}

// 清空路由
function resetRouter() {
  let routes = router.getRoutes()
  routes.forEach((item) => {
    if (item.path) {
      router.removeRoute(item.path)
    }
  })
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: any, lastRouter = false) {
  return asyncRouterMap.filter((route: any) => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }

    if (route.children != null && route.children && route.children.length) {
      // 将子路由的路径拼接上父路由的路径
      route.children = route.children.map((item: any) => {
        item.path = route.path + '/' + item.path
        return item
      })
      route.children = filterAsyncRouter(route.children, route)
    }

    return true
  })
}
export const loadView = (view: any) => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

interface tokeListData {
  token: string
  userInfo: any
  menuRoutes: RouteRecordRaw[]
  roles: string[]
}

export const useUserInfoStore = defineStore('userInfo', {
  state(): tokeListData {
    return {
      token: sessionStorage.getItem('Authorization') || '',
      userInfo: {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
        code: '',
        uuid: ''
      }, // 静态路由是否展示
      menuRoutes: [],
      roles: []
    }
  },
  actions: {
    async login(userInfo: any) {
      const result = await LoginRegister(userInfo)
      if (result.code === 501) {
        ElMessage.error(result.msg)
        return
      } else if (result.code === 502) {
        ElMessage.error('密码有误请检查')
        return
      } else if (result.code === 503) {
        ElMessage.error(result.msg)
        return result
      } else if (result.code === 508) {
        ElMessage.error(result.msg)
        return result
      } else if (result.code === 504) {
        ElMessage.error(result.msg)
        return result
      } else if (result.code === 500) {
        ElMessage.error(result.msg)
        return result
      } else {
        this.token = result.data.Authorization
        // let userInfoList = JSON.stringify(result.data.userInfo)
        // sessionStorage.setItem('userInfo', userInfoList)
        // sessionStorage.setItem('name', result.data.name)
        sessionStorage.setItem('Authorization', result.data.access_token)
        // JMessage.success('登录成功，请选择系统')
        router.push('/selectSystem')
        return 'ok'
      }
    },

    // 获取用户信息
    async getInfo() {
      return new Promise(async (resolve, reject) => {
        const system = sessionStorage.getItem('system')
        const res = (await request.get(`/system/user/getInfo`)) as any // 获取用户信息
        this.roles = res.roles
        // 检查缓存中是否存在头像数据
        const cachedAvatar = sessionStorage.getItem('userAvatar')
        const cachedAvatarPath = sessionStorage.getItem('userAvatarPath')
        
        // 获取新的头像数据
        request({
          url: fullFilePath(res.user.avatar),
          method: 'get',
          responseType: 'blob'
        }).then((blobData) => {
          const objectUrl = URL.createObjectURL(blobData)
          // 将新的头像数据存入缓存
          sessionStorage.setItem('userAvatar', objectUrl)
        })
        sessionStorage.setItem('userAvatarPath', res.user.avatar)
        sessionStorage.setItem('userInfo', JSON.stringify(res.user))
        if (!sessionStorage.getItem('company')) sessionStorage.setItem('company', JSON.stringify(res.company))
        const routers = (await request.get(`/system/menu/getRouters?systemId=${system}`)) as any // 获取路由
        if (routers.code === 200) {
          const sdata = JSON.parse(JSON.stringify(routers.data))
          const rdata = JSON.parse(JSON.stringify(routers.data))
          const rewriteRoutes = filterAsyncRouter(rdata, false)
          this.menuRoutes = filterAsyncRouter(sdata, false)
          rewriteRoutes.forEach((item: any) => {
            console.log(item)
            router.addRoute(item)
          })
          console.log(rewriteRoutes, router.getRoutes())

          resolve(rewriteRoutes)
        } else {
          JMessage.error(routers.msg)
          this.logout()
          router.push('/login')
          reject(routers.msg)
        }
      })
    },

    async reset() {
      this.token = ''
      this.userInfo = {}
      sessionStorage.removeItem('Authorization')
      sessionStorage.removeItem('system')
      sessionStorage.removeItem('userInfo')
      sessionStorage.removeItem('company')
      resetRouter()
    },

    async logout() {
      try {
        this.reset()
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    }
  }
})

export function getUserInfo() {
  return request({
    url: '/system/user/getInfo',
    method: 'get'
  })
}